<html>
<head>

<title>Groovy Goodness: Delete Non-empty Directory Recursively with File</title>

<script language="javascript" src="scripts/shCore.js"></script> 
<script language="javascript" src="scripts/shLegacy.js"></script> 
<script language="javascript" src="scripts/shBrushJava.js"></script> 
<script language="javascript" src="scripts/shBrushXml.js"></script> 
<script language="javascript" src="scripts/shBrushJScript.js"></script> 
<script language="javascript" src="scripts/shBrushGroovy.js"></script> 
<script language="javascript" src="scripts/shBrushPlain.js"></script> 
<script language="javascript" src="scripts/shBrushBash.js"></script> 
 
<link href="styles/reset.css" rel="stylesheet" type="text/css" />
<link href="styles/shCore.css" rel="stylesheet" type="text/css" />
<link type="text/css" rel="stylesheet" href="styles/shThemeRDark.css"/>
<link href="styles/blog.css" rel="stylesheet" type="text/css" />

</head>
<body>

<a href="index.html">Back to index</a>

<h3 class="post-title">Groovy Goodness: Delete Non-empty Directory Recursively with File</h3>

<div class="post">
<p>Groovy enhances the <code>File</code> class with several methods. One is the <code>deleteDir()</code> method. With this method we can delete a directory with all it's subdirectories and files. So the directory doesn't need to be empty to run this method.</p>
<pre class="brush:groovy">
def mainDir = new File('test') 
def subDir = new File(mainDir, 'app')
def file = new File(subDir, 'test.txt')

subDir.mkdirs()  // Create directories.
file &lt;&lt; 'sample'  // Create file and add contents.

assert mainDir.exists() &amp;&amp; subDir.exists() &amp;&amp; file.exists()

def result = mainDir.deleteDir()  // Returns true if all goes well, false otherwise.
assert result
assert !mainDir.exists() &amp;&amp; !subDir.exists() &amp;&amp; !file.exists() 
</pre
</div>

<script language="javascript"> 
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'scripts/clipboard.swf';
SyntaxHighlighter.defaults['first-line'] = 0;
SyntaxHighlighter.defaults['auto-links'] = false;
SyntaxHighlighter.all();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

</body>
</html>